<?php

namespace App\Http\Controllers\Import;

use App\Http\Controllers\Admin\CommonController;
use App\Http\Controllers\Controller;
use App\Models\BookTypes;
use App\Models\LibBook;
use App\Models\LibBookRecom;
use App\Models\LibBookType;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;


/**
 * excel导入功能
 */
class LibBookRecomImport extends Controller
{
    public $model = null;
    public $request = null;
    public $commonObj = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->model = new LibBookRecom();
        $this->commonObj = new CommonController();
    }

    /**
     * 馆藏书批量导入
     * @param file  excel 文件名
     * @param type_id   所属类型id
     * @param is_update  遇到重复数据，是否覆盖更新  1 更新  2 不更新 （默认2）
     */
    public function index()
    {
        set_time_limit(500);
        ini_set('memory_limit', '1024M');

        $is_update = $this->request->input('is_update', 2);
        $type_id = $this->request->input('type_id', '');

        $typeModel = new LibBookType();
        DB::beginTransaction();
        try {
            $data = $this->getData('file', 'book_import');

            // $success = 0;//成功个数
            $error = 0; //失败个数
            $error_msg = ''; //失败原因

            $LibApi = $this->getLibApiObj();
            foreach ($data as $key => $val) {
                $serial = $val[0];
                $barcode = trim($val[2]);
                //此书不允许推荐
                if (empty($barcode)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”条形码不能为空]';
                    continue;
                }

                //isbn可有可无 
                if (!empty($val[1])) {
                    $isbn = str_replace('-', '', $val[1]);
                    $isbn_len = strlen($isbn);
                    if ($isbn_len > 13) {
                        $isbn = substr($isbn, 0, 13);
                    }
                    //判断isbn规则
                    // $isbn_state = checkIsbn($ISBN);
                    // if (!$isbn_state) {
                    //     continue;
                    // }
                }
                $barcode_info = $LibApi->getAssetByBarcode($barcode);
                if ($barcode_info['code'] != 200) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”条形码获取馆藏书籍失败]';
                    continue;
                }

                $temp_data = $this->setBookAddData($barcode_info, $barcode, $isbn);
                //自定义分类
                /*           $type_name = !empty($val[3]) ? $val[3] : null; //类型可有可无 
                $new_type_id = empty($type_name) ? $type_id : $typeModel->getTypeId($type_name); //获取列表类型id
                $temp_data['type_id'] = $new_type_id ? $new_type_id : $type_id; */

                //获取中途分类法的类型
                $new_type_id = $this->getTypeId($barcode_info['content']['classno']); //获取列表类型id
                $temp_data['type_id'] = $new_type_id ? $new_type_id : $type_id;

                //判断条形码是否存在
                $bookIsExists = $this->model->nameIsExists($barcode, 'barcode');
                if (empty($bookIsExists)) {
                    $libBookRecomModel = new LibBookRecom();
                    $libBookRecomModel->add($temp_data); //覆盖更新数据
                } else {
                    if ($is_update == 1) {
                        $temp_data['id'] = $bookIsExists->id;
                        $this->model->change($temp_data); //覆盖更新数据
                    } else {
                        $error++;
                        $error_msg .= '[序号：“' . $serial . '” 条形码:' . $barcode . ' 已存在,不允许重复添加]';
                        continue;
                    }
                }
            }

            DB::commit();
            $return_msg = "导入成功，" . '错误: ' . $error . ' 个';
            if ($error) $return_msg .= '错误原因:' . $error_msg;

            return $this->commonObj->returnApi(200, $return_msg, true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->commonObj->returnApi(202, $e->getMessage());
        }
    }
    /**
     * 组装书籍数据
     * @param $data 数组数据
     */
    public function setBookAddData($data, $barcode, $isbn = null)
    {
        $temp_data = [];
        $temp_data['metaid'] = $data['content']['metaid'];
        $temp_data['metatable'] = $data['content']['metatable'];
        //   $temp_data['isbn'] = !empty($isbn) ? $isbn : str_replace('-', '', $data['content']['isbn']);
        $temp_data['isbn'] = !empty($data['content']['isbn']) ? str_replace('-', '', $data['content']['isbn']) : $isbn;
        $temp_data['book_name'] = $data['content']['book_name'];
        $temp_data['author'] = $data['content']['author'];
        $temp_data['old_isbn'] =  $data['content']['isbn'];
        $temp_data['price'] = $data['content']['price'];
        $temp_data['book_num'] = $data['content']['book_num'];
        $temp_data['press'] =  $data['content']['press'];
        $temp_data['pre_time'] = $data['content']['pre_time'];
        $temp_data['intro'] = $data['content']['intro'];
        $temp_data['barcode'] = $barcode;

        return $temp_data;
    }

    /**
     * 处理数据
     * @param $file_name  上传文件名 
     * @param $file_dir  存放文件夹 
     */
    public function getData($file_name = 'file', $file_dir = 'file')
    {
        if ($this->request->file($file_name) == null) throw new Exception('请添加Excel表格......'); // return $this->returnApi(202, '请添加Excel表格......');

        //接收前台文件
        if (empty($_FILES[$file_name]['name'])) throw new Exception('上传文件不能为空'); //return $this->returnApi(202, "上传文件不能为空");
        if (empty($_FILES[$file_name]['size']) || $_FILES[$file_name]['size'] > 5242880) throw new Exception('上传文件不能大于5M'); //return $this->returnApi(202, "上传文件不能大于5M");

        //判断文件名
        $name = explode('.', $_FILES[$file_name]['name'])[1];
        if ($name !== 'xls' && $name !== 'xlsx') throw new Exception('上传文件后缀名不允许，只能上传 .xls 或 .xlsx 的文件'); //return $this->returnApi(202, "上传文件后缀名不允许，只能上传 .xls 或 .xlsx 的文件");

        // 这个方法是 自定义文件名 文件上传方法 。 将获取到的Excel文件 保存到/public/upload/book_import/ 文件中。
        $foldername =  $file_dir . '/' . date('Y-m-d'); //$file_name.'/'.date('Y-m-d')  存放路径，按日志存储
        $file = $this->request->file($file_name)->store($foldername);

        if ($file) {
            //$this->request->file($file_name)->getRealPath(); 获取临时文件地址
            $file_addr = public_path('uploads') . '/' . $file; //完整地址
            /*  Excel::load($file_addr, function ($reader) {return $reader->all();}); */
            $delTitle = 1; //指定头行数  删除它
            $excel = new Import($delTitle);
            Excel::import($excel, $file_addr);
            if ($excel->data) {
                return $excel->data->toArray(); //获取所有的数据（数组）
            }
            throw new Exception('导入失败');
        }
        throw new Exception('请添加Excel表格......'); //return $this->returnApi(202, "导入失败");
    }

    /**
     * 获取中图分类法的id
     */
    public function getTypeId($book_num)
    {
        if (empty($book_num)) {
            return 0;
        }
        $letter = strtoupper(substr($book_num, 0, 1));
        $type_id = BookTypes::where('classify', $letter)->value('id');
        return $type_id ? $type_id : 0;
    }
}
